package com.zsd.android.glidelib.network;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;

import com.zsd.android.glidelib.resource.Value;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class LoadDataManager implements ILoadData, Runnable {

    private Context mContext;
    private String path;
    private ResponseListener listener;

    @Override
    public Value loadResource(Context mContext, String url, ResponseListener listener) {
        this.mContext = mContext;
        this.path = url;
        this.listener = listener;
        //加载 网络图片
        Uri uri = Uri.parse(url);
        String scheme = uri.getScheme();
        if ("HTTP".equalsIgnoreCase(scheme) || "HTTPS".equalsIgnoreCase(scheme)) {
            new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                    60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()).execute(this);
        } else {
            //SD卡加载使用Value返回
        }

        return null;
    }

    @Override
    public void run() {
        InputStream is = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(path);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            final int responseCode = connection.getResponseCode();
            if (HttpURLConnection.HTTP_OK == responseCode) {
                is = connection.getInputStream();
                final Bitmap bitmap = BitmapFactory.decodeStream(is);
                //回调成功
                //切换主线程
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Value value = Value.getInstance();
                        value.setBitmap(bitmap);
                        listener.success(value);
                    }
                });
            } else {
                //回调失败
                //切换主线程
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        listener.failed(new IllegalStateException("请求失败：" + responseCode));
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
